package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.AdPositionMapper;
import org.example.pojo.AdPosition;
import org.example.pojo.AdPositionVO;
import org.example.pojo.Client;
import org.example.pojo.PageBean;
import org.example.service.AdPositionService;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AdPositionServiceImpl implements AdPositionService {

    @Autowired
    private AdPositionMapper adPositionMapper;

    @Override
    public void add(AdPosition adPosition) {
        //设置时间
        adPosition.setCreateTime(LocalDateTime.now());
        adPosition.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        adPosition.setCreateUser(id);

        adPositionMapper.add(adPosition);
    }

    @Override
    public void delete(Integer id) {
        adPositionMapper.delete(id);
    }

    @Override
    public PageBean<AdPosition> list(Integer pageNum, Integer pageSize, Integer clientId) {

        //1.创建PageBean对象
        PageBean<AdPosition> pageBean = new PageBean<>();
        //2.开启分页查询PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<AdPosition> as = adPositionMapper.list(userId,clientId);
        Page<AdPosition> pageInfo = (Page<AdPosition>) as;

        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setItems(pageInfo.getResult());

        return pageBean;
    }

    @Override
    @Transactional
    public void update(AdPosition adPosition) {
        adPosition.setUpdateTime(LocalDateTime.now());
        System.out.println(adPosition);
        adPositionMapper.update(adPosition);
    }

    @Override
    public AdPosition detail(Integer id) {
        return adPositionMapper.detail(id);
    }

    @Override
    public PageBean<AdPositionVO> getByClientName(Integer pageNum, Integer pageSize, String clientName) {
        //1.创建PageBean对象
        PageBean<AdPositionVO> pageBean = new PageBean<>();
        //2.开启分页查询PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<AdPositionVO> as = adPositionMapper.getByClientName(userId,clientName);
        Page<AdPositionVO> pageInfo = (Page<AdPositionVO>) as;

        pageBean.setTotal(pageInfo.getTotal());
        pageBean.setItems(pageInfo.getResult());

        return pageBean;
    }
}
